# !/usr/bin/python
# -*- coding: UTF-8 -*-
# @author:qiaofinn
# @file:wechat_applet.py
# @time:2020/09/09
import base64
import json
import os
from urllib import request

import requests
from django.conf import settings
from utils.exceptions import CustomError


class WeChatApplet(object):
    '''微信小程序'''

    def __init__(self):
        self.appid = settings.WECHAT_APPLET['appid']
        self.appsecret = settings.WECHAT_APPLET['secret']

    def get_access_token(self):
        # 获取小程序全局唯一后台接口调用凭据（access_token）
        get_access_token_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={APPID}&secret={APPSECRET}'.format(
            APPID=self.appid, APPSECRET=self.appsecret)
        res = requests.get(get_access_token_url).json()

        access_token = res.get('access_token', None)
        if not access_token:
            raise CustomError(u'微信请求获取access_token失败！')

        return access_token

    def wx_check_content(self, content):
        # 微信敏感词校验
        access_token = self.get_access_token()
        sec_check_url = 'https://api.weixin.qq.com/wxa/msg_sec_check?access_token={access_token}'.format(
            access_token=access_token)
        headers = {
            'content-type': 'application/json'
        }
        data = {'content': content.encode("utf-8").decode("latin1")}
        sec_check_res = requests.post(sec_check_url, data=json.dumps(data, ensure_ascii=False), headers=headers).json()
        if sec_check_res['errcode'] != 0:
            raise CustomError(u'含有违法违规内容！')

    def get_wx_acode_unlimit(self):
        # 获取小程序码
        access_token = self.get_access_token()
        get_wx_acode_unlimit_url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={access_token}'.format(
            access_token=access_token)
        scene = '17616153358'  # 用户的手机号
        textmod = {"scene": scene, "page": "pages/product/product", "width": 430, "auto_color": True, "is_hyaline": False}
        textmod = json.dumps(textmod).encode(encoding='utf-8')
        header_dict = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko',
                       "Content-Type": "application/json"}
        req = request.Request(url=get_wx_acode_unlimit_url, data=textmod, headers=header_dict)
        res = request.urlopen(req)
        res = res.read()
        b64str = base64.b64encode(res)
        imgdata = base64.b64decode(b64str)
        file = open(os.path.join(settings.BASE_DIR, 'uploads/scan1.png'), 'wb+')
        file.write(imgdata)
        file.close()
        return ''
